package com.educhains.web.ctrl.frontend;

import com.educhains.module.chat.service.MessageService;
import com.educhains.module.chat.vo.Message;
import com.educhains.module.user.service.UserService;
import com.educhains.module.user.vo.User;
import com.educhains.web.util.SessionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

//TODO interceptor
@Controller
@RequestMapping("/chat")
public class ChatCtrl {

    @Autowired
    private UserService userService = null;

    @Autowired
    private MessageService messageService = null;

    @RequestMapping("/index")
    public String index(HttpServletRequest request) {
        User sessionUser = SessionUtils.getUser(request);
        List<User> users = userService.selectUserList();
        List<User> result = new ArrayList<User>();
        for (User user : users) {
            if (user.getUserId() != sessionUser.getUserId()) result.add(user);
        }
        request.setAttribute("users", result);
        return "frontend/chat/index";
    }

    @RequestMapping("/getChatLog")
    @ResponseBody
    public List<Message> getChatLog(HttpServletRequest request) {
        //TODO pagination
        String messageFromId = request.getParameter("messageFromId");
        String messageToId = request.getParameter("messageToId");
        return messageService.getChatLog(messageFromId, messageToId);
    }
}
